const http = require('http');
const fs = require('fs-extra');
const path = require('path');
const Multiparty = require('multiparty');
const filePath = path.resolve('./upfile')
const getPost = (req) => {
  return new Promise((resolve) => {
    let buf = Buffer.from('');
    req.on('data', function (chunk){
      buf = Buffer.concat([buf,chunk]);
    })
    req.on('end', function(){
      resolve(JSON.parse(buf.toString()))
    })
  })
}
const pipeStream = (chunkPath,streams) => new Promise((resolve) => {
  // 创建可读流
  const readStream = fs.createReadStream(chunkPath);
  readStream.on('end', function(){
    // 删除切片
    fs.unlinkSync(chunkPath);
    resolve();
  })
  readStream.pipe(streams);
})
const mergeChunk = async (TargetPath,filename,size) => {
  const chunkDir = path.join(filePath,filename);
  const chunkPaths = await fs.readdir(chunkDir);
  // 切片排序
  chunkPaths.sort((a,b) => {
    let a_index = a.split('_')[1];
    let b_index = b.split('_')[1];
    return a_index - b_index;
  })
  await Promise.all(
    chunkPaths.map((chunkname, index) => 
      pipeStream(
        path.join(chunkDir,chunkname),
        fs.createWriteStream(TargetPath, {
          start: index * size,
          end: (index + 1) * size
        })
      )
    )
  )
  // 删除文件夹
  await fs.rmdir(chunkDir);
}
const server = http.createServer(async (req,res) => {
  if(req.url === '/favicon.ico'){
    res.end('')
    return;
  }
  if(req.url === '/'){
    res.end(fs.readFileSync(path.resolve('client','index.html')));
    return;
  }
  if(req.url === '/uploadChunk'){ // 收集切片
    const multiparty = new Multiparty.Form();
    multiparty.parse(req, async (err,{chunkname,filename},{file}) => {
      if(err){
        console.log(err);
        return;
      }
      let [chunk_name] = chunkname;
      let [file_name] = filename;
      let {path:chunk_path} = file[0]
      const chunkDir = path.resolve(filePath, file_name);
      if(!fs.existsSync(chunkDir)){
        await fs.mkdirs(chunkDir);
      }
      // 本地chunk移到服务端chunk
      await fs.move(chunk_path, path.join(chunkDir, chunk_name));
      res.end('create chunk file');
    })
    return;
  }
  if(req.url === '/mergeChunk'){  // 所有切片收集成功和合并切片
    const {filename,SIZE:size} = await getPost(req);
    const TargetPath = path.join(filePath,'_target',filename);
    await mergeChunk(TargetPath,filename,size)
    res.end('merage success');
  }
})

server.listen(3000, ()=> {
  console.log('请访问 \n http://localhost:3000 \n 打开页面')
})